<?php
declare (strict_types = 1);

namespace app\common\model\system;

use app\common\utils\facade\FileUtil;
use think\Model;

/**
 * @mixin think\Model
 */
class Setting extends Model
{
    const UP_FIELD = 'logo';
    const UP_FOLDER = 'logo';

    // 设置字段信息
    protected $schema = [
        'id'            => 'int',
        'appname'       => 'string',
        'description'   => 'string',
        'keywords'      => 'string',
        'logo'          => 'string',
        'record'        => 'string',
        'email'         => 'string',
        'about'         => 'string',
        'update_time'   => 'int',
    ];

    // 类型转换
    protected $type = [
        'id'            => 'integer',
    ];

    //封面获取器(页面显示图片)
    public function getLogoUrlAttr()
    {
        return empty($this->getAttr('logo')) ? config('app.default_logo') : showImg($this->getAttr('logo'));
    }

    //保存之前转移图片到永久地址
    public static function onBeforeWrite(Model $model){
        //修改话题(如果修改了图片 就先删除原有图片

        //删除图片
        if ($model->isExists() && array_key_exists('logo', $model->getChangedData())){
            $real_file = static::getRealPath($model->getOrigin('logo'));
            if(is_file($real_file)) FileUtil::unlinkFile($real_file);
        }

        //移动到永久目录
        if(!empty($model->logo) && ( !$model->isExists() || array_key_exists('logo', $model->getChangedData()))){
            $ori_img = static::getTmpPath($model->logo);
            $des_img = static::getRealPath($model->logo);

            if(is_file($ori_img)){
                if ( !FileUtil::moveFile($ori_img, $des_img) )
                    return false;
            }
        }

        return true;
    }

    //获取临时文件的绝对路径
    private static function getTmpPath($file){
        return config('filesystem.disks.local.root') . DS. $file;
    }
    //获取永久文件的绝对路径
    private static function getRealPath($file){
        return config('filesystem.disks.public.root') .DS. $file;
    }
}
